define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yungift/card/code/index' + location.search,
                    add_url: 'yungift/card/code/add' + location.search,
                    edit_url: 'yungift/card/code/edit' + location.search,
                    // del_url: 'yungift/card/code/del',
                    multi_url: 'yungift/card/code/multi',
                    import_url: 'yungift/card/code/import' + location.search,
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        // 该列为复选框字段,如果后台的返回state值将会默认选中
                        {
                            field: 'state',
                            checkbox: true
                        },
                        // sortable为是否排序,operate为搜索时的操作符,visible表示是否可见
                        {
                            field: 'id',
                            title: 'ID',
                            sortable: true,
                            operate: false
                        },
                        {
                            field: 'card_id',
                            title: __('礼卡'),
                            searchList: Config.cardList,
                            formatter: function (value, row, index) {
                                return row.card_data ? row.card_data.name : '已删除';
                            },
                            visible: !Config.cardId,
                            searchable: !Config.cardId
                        },
                        {
                            field: 'number',
                            title: __('卡号'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                        },
                        {
                            field: 'password',
                            title: __('卡密'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                            formatter: function (value, row, index) {
                                return row.password_mix;
                            }
                        },
                        {
                            field: 'phone',
                            title: __('手机号'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                            formatter: function (value, row, index) {
                                return row.phone_mix;
                            }
                        },
                        {
                            field: 'note',
                            title: __('备注'),
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索',
                        },
                        {
                            field: 'chance_use',
                            title: __('已兑次数'),
                            sortable: true,
                            operate: false,
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: Config.statusList,
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'updated_at',
                            title: __('Update time'),
                            sortable: true,
                            operate: false,
                            formatter: Table.api.formatter.datetime,
                        },
                        {
                            field: 'created_at',
                            title: __('Create time'),
                            sortable: true,
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        // 操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                        {
                            field: 'operate',
                            width: "150px",
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'plus',
                                    text: __('二维码'),
                                    title: __('兑换二维码'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-qrcode',
                                    url: function (row) {
                                        return 'yungift/qrcode/preview?scene=card&cid=' + row.card_id + '&number=' + row.number;
                                    },
                                    extend: 'data-area=\'["300px","500px"]\'',
                                },
                                {
                                    name: 'order',
                                    text: __('订单'),
                                    title: function (row) {
                                        return __('相关订单') + ' - ' + row.number;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    visible: function (row) {
                                        return row.chance_use > 0;
                                    },
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'yungift/gift/order/index?model_type=card&model_account=' + row.id;
                                    },
                                },
                                {
                                    name: 'swap',
                                    text: __('设置兑换过'),
                                    title: function (row) {
                                        return __('设置兑换过');
                                    },
                                    classname: 'btn btn-xs btn-success btn-magic btn-click',
                                    visible: function (row) {
                                        return row.status !== 4 && Config.swap;
                                    },
                                    icon: 'fa fa-magic',
                                    click: function(value, row, index) {
                                        Layer.confirm('确认要将此卡设置为兑换过吗？', {
                                            icon: 3,
                                            title: '提示',
                                            yes: function(index) {
                                                Layer.close(index);
                                                var loading = Layer.msg('设置中，请稍候...', {
                                                    icon: 16,
                                                    time: -1,
                                                    shade: [0.3, '#fff']
                                                });
                                                $.ajax({
                                                    url: 'yungift/card/code/swap?ids=' + row.id,
                                                    success: function(ret) {
                                                        Layer.close(loading);
                                                        Layer.alert(ret.msg);
                                                        if (ret.code === 1) {
                                                            table.bootstrapTable('refresh');
                                                        }
                                                    },
                                                    error: function(xhr) {
                                                        Layer.close(loading);
                                                        Layer.alert('请求失败: ' + xhr.status);
                                                    }
                                                });
                                            }
                                        });
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.operate
                        },
                    ],
                ],
                // 快捷搜索,这里可在控制器定义快捷搜索的字段
                search: false,
                // 启用普通表单搜索
                commonSearch: true,
                // 显示切换视图（table/card）按钮
                showToggle: false,
                // 显示导出按钮
                showExport: false,
                // 启用跨页选择
                maintainSelected: true,
                // 启用固定列
                fixedColumns: true,
                // 固定右侧列数
                fixedRightNumber: 1,
                // 可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
            });

            // 自定义export开始 ***************************
            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                console.log('options', options);
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field !== 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                console.log('search', search);
                $("input[name=search]", layero).val(options.searchText);
                $("input[name=ids]", layero).val(ids);
                $("input[name=filter]", layero).val(search.filter);
                $("input[name=op]", layero).val(search.op);
                $("input[name=columns]", layero).val(columns.join(','));
                $("form", layero).submit();
            };
            $(document).on("click", ".btn-export", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log('choose', ids, page, all);
                Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl('yungift/card/code/export' + location.search) + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '导出数据',
                    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        // 弹窗显示后，统一3个按钮的样式
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    },
                    yes: function (index, layero) {
                        submitForm(ids.join(","), layero);
                        Layer.close(index);
                        return true;
                    },
                    btn2: function (index, layero) {
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        submitForm(ids.join(","), layero);
                        return true;
                    },
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        return true;
                    }
                })
            });
            $(document).on("click", ".btn-export-qrcode", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;
                console.log('choose', ids, page, all);
                Layer.confirm("请选择下载的选项，二维码请妥善保存！！！<form action='" + Fast.api.fixurl('yungift/card/code/exportQrcode' + location.search) + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '下载兑换码',
                    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        // 弹窗显示后，统一3个按钮的样式
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    },
                    yes: function (index, layero) {
                        submitForm(ids.join(","), layero);
                        Layer.close(index);
                        return true;
                    },
                    btn2: function (index, layero) {
                        var ids = [];
                        $.each(page, function (i, j) {
                            ids.push(j.id);
                        });
                        submitForm(ids.join(","), layero);
                        return true;
                    },
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        return true;
                    }
                })
            });
            // 自定义export结束 ***************************

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        generate: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {  // 渲染的方法
            },
            events: {  // 绑定事件的方法
            }
        }
    };
    return Controller;
});
